import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type {
  KnowledgeBase,
  KnowledgeDocument,
  KnowledgeChunk,
  CreateKnowledgeBaseRequest,
  UpdateKnowledgeBaseRequest,
  CreateDocumentRequest,
  UpdateDocumentRequest,
} from "@/types/knowledge";
import type { ApiResponse } from "@/types/api";
import { knowledgeApi } from "@/api/services";
import {
  KNOWLEDGE_BASE_STATUS,
  DOCUMENT_STATUS,
  CHUNK_STATUS,
} from "@/constants";
import { generateId } from "@/utils";

/**
 * 知识库状态管理
 */
export const useKnowledgeStore = defineStore("knowledge", () => {
  // 状态
  const knowledgeBases = ref<KnowledgeBase[]>([]);
  const currentKnowledgeBase = ref<KnowledgeBase | null>(null);
  const documents = ref<Map<string, KnowledgeDocument[]>>(new Map());
  const chunks = ref<Map<string, KnowledgeChunk[]>>(new Map());
  const isLoading = ref(false);
  const isProcessing = ref(false);
  const isIndexing = ref(false);
  const error = ref<string | null>(null);
  const hasMoreKnowledgeBases = ref(true);
  const hasMoreDocuments = ref<Map<string, boolean>>(new Map());
  const hasMoreChunks = ref<Map<string, boolean>>(new Map());
  const totalKnowledgeBases = ref(0);
  const totalDocuments = ref<Map<string, number>>(new Map());
  const totalChunks = ref<Map<string, number>>(new Map());
  const searchQuery = ref("");
  const selectedCategory = ref<string>("");
  const selectedTags = ref<string[]>([]);
  const sortBy = ref<string>("updatedAt");
  const sortOrder = ref<"asc" | "desc">("desc");
  const uploadProgress = ref<Map<string, number>>(new Map());
  const processingStatus = ref<Map<string, string>>(new Map());

  // 计算属性
  const filteredKnowledgeBases = computed(() => {
    let filtered = [...knowledgeBases.value];

    // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase();
      filtered = filtered.filter(
        (kb) =>
          kb.name.toLowerCase().includes(query) ||
          kb.description.toLowerCase().includes(query) ||
          kb.tags.some((tag) => tag.toLowerCase().includes(query)),
      );
    }

    // 分类过滤
    if (selectedCategory.value) {
      filtered = filtered.filter(
        (kb) => kb.category === selectedCategory.value,
      );
    }

    // 标签过滤
    if (selectedTags.value.length > 0) {
      filtered = filtered.filter((kb) =>
        selectedTags.value.every((tag) => kb.tags.includes(tag)),
      );
    }

    // 排序
    filtered.sort((a, b) => {
      let aValue: any, bValue: any;

      switch (sortBy.value) {
        case "name":
          aValue = a.name;
          bValue = b.name;
          break;
        case "createdAt":
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
        case "updatedAt":
          aValue = new Date(a.updatedAt).getTime();
          bValue = new Date(b.updatedAt).getTime();
          break;
        case "documentCount":
          aValue = a.documentCount || 0;
          bValue = b.documentCount || 0;
          break;
        case "size":
          aValue = a.totalSize || 0;
          bValue = b.totalSize || 0;
          break;
        default:
          return 0;
      }

      if (typeof aValue === "string") {
        return sortOrder.value === "asc"
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue);
      } else {
        return sortOrder.value === "asc" ? aValue - bValue : bValue - aValue;
      }
    });

    return filtered;
  });

  const currentDocuments = computed(() => {
    if (!currentKnowledgeBase.value) return [];
    return documents.value.get(currentKnowledgeBase.value.id) || [];
  });

  const availableCategories = computed(() => {
    const categories = new Set(knowledgeBases.value.map((kb) => kb.category));
    return Array.from(categories).sort();
  });

  const availableTags = computed(() => {
    const tags = new Set<string>();
    knowledgeBases.value.forEach((kb) => {
      kb.tags.forEach((tag) => tags.add(tag));
    });
    return Array.from(tags).sort();
  });

  const getDocuments = computed(() => {
    return (knowledgeBaseId: string) =>
      documents.value.get(knowledgeBaseId) || [];
  });

  const getChunks = computed(() => {
    return (documentId: string) => chunks.value.get(documentId) || [];
  });

  const getUploadProgress = computed(() => {
    return (fileId: string) => uploadProgress.value.get(fileId) || 0;
  });

  const getProcessingStatus = computed(() => {
    return (documentId: string) => processingStatus.value.get(documentId) || "";
  });

  /**
   * 加载知识库列表
   */
  const loadKnowledgeBases = async (
    page: number = 1,
    limit: number = 20,
    refresh: boolean = false,
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const params = {
        page,
        limit,
        search: searchQuery.value,
        category: selectedCategory.value,
        tags: selectedTags.value,
        sortBy: sortBy.value,
        sortOrder: sortOrder.value,
      };

      const response = await knowledgeApiService.getKnowledgeBases(params);

      if (response.success) {
        if (page === 1 || refresh) {
          knowledgeBases.value = response.data.knowledgeBases;
        } else {
          knowledgeBases.value.push(...response.data.knowledgeBases);
        }

        hasMoreKnowledgeBases.value = response.data.hasMore;
        totalKnowledgeBases.value = response.data.total;

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载知识库失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 获取知识库详情
   */
  const getKnowledgeBaseById = async (knowledgeBaseId: string) => {
    try {
      // 先从本地查找
      let knowledgeBase = knowledgeBases.value.find(
        (kb) => kb.id === knowledgeBaseId,
      );
      if (knowledgeBase) {
        return { success: true, data: knowledgeBase };
      }

      // 从API获取
      const response =
        await knowledgeApiService.getKnowledgeBase(knowledgeBaseId);

      if (response.success) {
        knowledgeBase = response.data;

        // 更新本地列表
        const index = knowledgeBases.value.findIndex(
          (kb) => kb.id === knowledgeBaseId,
        );
        if (index !== -1) {
          knowledgeBases.value[index] = knowledgeBase;
        } else {
          knowledgeBases.value.push(knowledgeBase);
        }

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "获取知识库详情失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取知识库详情失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 创建知识库
   */
  const createKnowledgeBase = async (data: CreateKnowledgeBaseRequest) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.createKnowledgeBase(data);

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeBases.value.unshift(knowledgeBase);
        totalKnowledgeBases.value++;

        // 初始化文档列表
        documents.value.set(knowledgeBase.id, []);
        hasMoreDocuments.value.set(knowledgeBase.id, false);
        totalDocuments.value.set(knowledgeBase.id, 0);

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "创建知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "创建知识库失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 更新知识库
   */
  const updateKnowledgeBase = async (
    knowledgeBaseId: string,
    data: UpdateKnowledgeBaseRequest,
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.updateKnowledgeBase(
        knowledgeBaseId,
        data,
      );

      if (response.success) {
        const updatedKnowledgeBase = response.data;

        // 更新本地列表
        const index = knowledgeBases.value.findIndex(
          (kb) => kb.id === knowledgeBaseId,
        );
        if (index !== -1) {
          knowledgeBases.value[index] = updatedKnowledgeBase;
        }

        // 更新当前知识库
        if (currentKnowledgeBase.value?.id === knowledgeBaseId) {
          currentKnowledgeBase.value = updatedKnowledgeBase;
        }

        return { success: true, data: updatedKnowledgeBase };
      } else {
        error.value = response.message || "更新知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新知识库失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 删除知识库
   */
  const deleteKnowledgeBase = async (knowledgeBaseId: string) => {
    try {
      const response =
        await knowledgeApiService.deleteKnowledgeBase(knowledgeBaseId);

      if (response.success) {
        // 从本地列表移除
        knowledgeBases.value = knowledgeBases.value.filter(
          (kb) => kb.id !== knowledgeBaseId,
        );
        totalKnowledgeBases.value--;

        // 如果删除的是当前知识库，清除当前知识库
        if (currentKnowledgeBase.value?.id === knowledgeBaseId) {
          currentKnowledgeBase.value = null;
        }

        // 清除相关数据
        documents.value.delete(knowledgeBaseId);
        hasMoreDocuments.value.delete(knowledgeBaseId);
        totalDocuments.value.delete(knowledgeBaseId);

        return { success: true };
      } else {
        error.value = response.message || "删除知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除知识库失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 设置当前知识库
   */
  const setCurrentKnowledgeBase = async (knowledgeBaseId: string) => {
    const knowledgeBase = knowledgeBases.value.find(
      (kb) => kb.id === knowledgeBaseId,
    );
    if (knowledgeBase) {
      currentKnowledgeBase.value = knowledgeBase;

      // 如果还没有加载文档，则加载
      if (!documents.value.has(knowledgeBaseId)) {
        await loadDocuments(knowledgeBaseId);
      }

      return { success: true, data: knowledgeBase };
    } else {
      error.value = "知识库不存在";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载文档列表
   */
  const loadDocuments = async (
    knowledgeBaseId: string,
    page: number = 1,
    limit: number = 20,
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.getDocuments(knowledgeBaseId, {
        page,
        limit,
      });

      if (response.success) {
        if (page === 1) {
          documents.value.set(knowledgeBaseId, response.data.documents);
        } else {
          const existingDocuments = documents.value.get(knowledgeBaseId) || [];
          documents.value.set(knowledgeBaseId, [
            ...existingDocuments,
            ...response.data.documents,
          ]);
        }

        hasMoreDocuments.value.set(knowledgeBaseId, response.data.hasMore);
        totalDocuments.value.set(knowledgeBaseId, response.data.total);

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载文档失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 上传文档
   */
  const uploadDocument = async (
    knowledgeBaseId: string,
    file: File,
    options: any = {},
  ) => {
    try {
      isProcessing.value = true;
      error.value = null;

      const fileId = generateId();
      uploadProgress.value.set(fileId, 0);

      const response = await knowledgeApiService.uploadDocument(
        knowledgeBaseId,
        file,
        {
          ...options,
          onProgress: (progress: number) => {
            uploadProgress.value.set(fileId, progress);
          },
        },
      );

      if (response.success) {
        const document = response.data;

        // 添加到文档列表
        const knowledgeBaseDocuments =
          documents.value.get(knowledgeBaseId) || [];
        knowledgeBaseDocuments.unshift(document);
        documents.value.set(knowledgeBaseId, knowledgeBaseDocuments);

        // 更新计数
        const currentTotal = totalDocuments.value.get(knowledgeBaseId) || 0;
        totalDocuments.value.set(knowledgeBaseId, currentTotal + 1);

        // 更新知识库统计
        const knowledgeBase = knowledgeBases.value.find(
          (kb) => kb.id === knowledgeBaseId,
        );
        if (knowledgeBase) {
          knowledgeBase.documentCount = (knowledgeBase.documentCount || 0) + 1;
          knowledgeBase.totalSize = (knowledgeBase.totalSize || 0) + file.size;
        }

        // 清除上传进度
        uploadProgress.value.delete(fileId);

        return { success: true, data: document };
      } else {
        uploadProgress.value.delete(fileId);
        error.value = response.message || "上传文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "上传文档失败";
      return { success: false, message: error.value };
    } finally {
      isProcessing.value = false;
    }
  };

  /**
   * 批量上传文档
   */
  const uploadDocuments = async (
    knowledgeBaseId: string,
    files: File[],
    options: any = {},
  ) => {
    const results = [];

    for (const file of files) {
      const result = await uploadDocument(knowledgeBaseId, file, options);
      results.push({ file: file.name, ...result });
    }

    return { success: true, data: results };
  };

  /**
   * 更新文档
   */
  const updateDocument = async (
    knowledgeBaseId: string,
    documentId: string,
    data: UpdateDocumentRequest,
  ) => {
    try {
      const response = await knowledgeApiService.updateDocument(
        knowledgeBaseId,
        documentId,
        data,
      );

      if (response.success) {
        const updatedDocument = response.data;

        // 更新本地列表
        const knowledgeBaseDocuments =
          documents.value.get(knowledgeBaseId) || [];
        const index = knowledgeBaseDocuments.findIndex(
          (doc) => doc.id === documentId,
        );
        if (index !== -1) {
          knowledgeBaseDocuments[index] = updatedDocument;
          documents.value.set(knowledgeBaseId, knowledgeBaseDocuments);
        }

        return { success: true, data: updatedDocument };
      } else {
        error.value = response.message || "更新文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新文档失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 删除文档
   */
  const deleteDocument = async (
    knowledgeBaseId: string,
    documentId: string,
  ) => {
    try {
      const response = await knowledgeApiService.deleteDocument(
        knowledgeBaseId,
        documentId,
      );

      if (response.success) {
        // 从本地列表移除
        const knowledgeBaseDocuments =
          documents.value.get(knowledgeBaseId) || [];
        const filteredDocuments = knowledgeBaseDocuments.filter(
          (doc) => doc.id !== documentId,
        );
        documents.value.set(knowledgeBaseId, filteredDocuments);

        // 更新计数
        const currentTotal = totalDocuments.value.get(knowledgeBaseId) || 0;
        totalDocuments.value.set(
          knowledgeBaseId,
          Math.max(0, currentTotal - 1),
        );

        // 更新知识库统计
        const knowledgeBase = knowledgeBases.value.find(
          (kb) => kb.id === knowledgeBaseId,
        );
        if (knowledgeBase) {
          knowledgeBase.documentCount = Math.max(
            0,
            (knowledgeBase.documentCount || 0) - 1,
          );
        }

        // 清除相关数据
        chunks.value.delete(documentId);
        hasMoreChunks.value.delete(documentId);
        totalChunks.value.delete(documentId);
        processingStatus.value.delete(documentId);

        return { success: true };
      } else {
        error.value = response.message || "删除文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除文档失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 批量删除文档
   */
  const deleteDocuments = async (
    knowledgeBaseId: string,
    documentIds: string[],
  ) => {
    try {
      const response = await knowledgeApiService.batchDeleteDocuments(
        knowledgeBaseId,
        { documentIds },
      );

      if (response.success) {
        // 从本地列表移除
        const knowledgeBaseDocuments =
          documents.value.get(knowledgeBaseId) || [];
        const filteredDocuments = knowledgeBaseDocuments.filter(
          (doc) => !documentIds.includes(doc.id),
        );
        documents.value.set(knowledgeBaseId, filteredDocuments);

        // 更新计数
        const currentTotal = totalDocuments.value.get(knowledgeBaseId) || 0;
        totalDocuments.value.set(
          knowledgeBaseId,
          Math.max(0, currentTotal - documentIds.length),
        );

        // 更新知识库统计
        const knowledgeBase = knowledgeBases.value.find(
          (kb) => kb.id === knowledgeBaseId,
        );
        if (knowledgeBase) {
          knowledgeBase.documentCount = Math.max(
            0,
            (knowledgeBase.documentCount || 0) - documentIds.length,
          );
        }

        // 清除相关数据
        documentIds.forEach((documentId) => {
          chunks.value.delete(documentId);
          hasMoreChunks.value.delete(documentId);
          totalChunks.value.delete(documentId);
          processingStatus.value.delete(documentId);
        });

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "批量删除文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "批量删除文档失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 搜索知识库
   */
  const searchKnowledgeBases = async (query: string, options: any = {}) => {
    searchQuery.value = query;
    return await loadKnowledgeBases(1, 20, true);
  };

  /**
   * 搜索文档
   */
  const searchDocuments = async (
    knowledgeBaseId: string,
    query: string,
    options: any = {},
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.searchDocuments(
        knowledgeBaseId,
        { query, ...options },
      );

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "搜索文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "搜索文档失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 问答搜索
   */
  const askQuestion = async (
    knowledgeBaseId: string,
    question: string,
    options: any = {},
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.askQuestion(knowledgeBaseId, {
        question,
        ...options,
      });

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "问答失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "问答失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 重建索引
   */
  const rebuildIndex = async (knowledgeBaseId: string) => {
    try {
      isIndexing.value = true;
      error.value = null;

      const response = await knowledgeApiService.rebuildIndex(knowledgeBaseId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "重建索引失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "重建索引失败";
      return { success: false, message: error.value };
    } finally {
      isIndexing.value = false;
    }
  };

  /**
   * 获取知识库统计
   */
  const getKnowledgeBaseStats = async (knowledgeBaseId: string) => {
    try {
      const response =
        await knowledgeApiService.getKnowledgeBaseStats(knowledgeBaseId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "获取统计失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取统计失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 导出知识库
   */
  const exportKnowledgeBase = async (
    knowledgeBaseId: string,
    format: string = "json",
  ) => {
    try {
      const response = await knowledgeApiService.exportKnowledgeBase(
        knowledgeBaseId,
        { format },
      );

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "导出失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "导出失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 导入知识库
   */
  const importKnowledgeBase = async (file: File) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.importKnowledgeBase(file);

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeBases.value.unshift(knowledgeBase);
        totalKnowledgeBases.value++;

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "导入失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "导入失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 设置过滤条件
   */
  const setFilters = async (filters: {
    category?: string;
    tags?: string[];
    sortBy?: string;
    sortOrder?: "asc" | "desc";
  }) => {
    if (filters.category !== undefined)
      selectedCategory.value = filters.category;
    if (filters.tags !== undefined) selectedTags.value = filters.tags;
    if (filters.sortBy !== undefined) sortBy.value = filters.sortBy;
    if (filters.sortOrder !== undefined) sortOrder.value = filters.sortOrder;

    return await loadKnowledgeBases(1, 20, true);
  };

  /**
   * 清除过滤条件
   */
  const clearFilters = async () => {
    searchQuery.value = "";
    selectedCategory.value = "";
    selectedTags.value = [];
    sortBy.value = "updatedAt";
    sortOrder.value = "desc";

    return await loadKnowledgeBases(1, 20, true);
  };

  /**
   * 清空所有数据
   */
  const clearAll = () => {
    knowledgeBases.value = [];
    currentKnowledgeBase.value = null;
    documents.value.clear();
    chunks.value.clear();
    hasMoreDocuments.value.clear();
    hasMoreChunks.value.clear();
    totalDocuments.value.clear();
    totalChunks.value.clear();
    uploadProgress.value.clear();
    processingStatus.value.clear();
    totalKnowledgeBases.value = 0;
    hasMoreKnowledgeBases.value = true;
    searchQuery.value = "";
    selectedCategory.value = "";
    selectedTags.value = [];
    error.value = null;
  };

  return {
    // 状态
    knowledgeBases,
    currentKnowledgeBase,
    documents,
    chunks,
    isLoading,
    isProcessing,
    isIndexing,
    error,
    hasMoreKnowledgeBases,
    hasMoreDocuments,
    hasMoreChunks,
    totalKnowledgeBases,
    totalDocuments,
    totalChunks,
    searchQuery,
    selectedCategory,
    selectedTags,
    sortBy,
    sortOrder,
    uploadProgress,
    processingStatus,

    // 计算属性
    filteredKnowledgeBases,
    currentDocuments,
    availableCategories,
    availableTags,
    getDocuments,
    getChunks,
    getUploadProgress,
    getProcessingStatus,

    // 方法
    loadKnowledgeBases,
    getKnowledgeBaseById,
    createKnowledgeBase,
    updateKnowledgeBase,
    deleteKnowledgeBase,
    setCurrentKnowledgeBase,
    loadDocuments,
    uploadDocument,
    uploadDocuments,
    updateDocument,
    deleteDocument,
    deleteDocuments,
    searchKnowledgeBases,
    searchDocuments,
    askQuestion,
    rebuildIndex,
    getKnowledgeBaseStats,
    exportKnowledgeBase,
    importKnowledgeBase,
    setFilters,
    clearFilters,
    clearAll,
  };
});
